package hhm.android.main

import android.util.Log
import android.util.SparseArray
import android.view.View
import android.widget.ImageView
import androidx.core.util.forEach
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.FragmentEvent
import hhm.android.base.fragment.NewLazyFragment
import hhm.android.library.bus.Bus
import hhm.android.library.utils.OnMultiClickListener
import siau.android.base.BottomSingleFamilySelectSheet
import siau.android.base.HttpHelper
import siau.android.base.SBApplication
import siau.android.base.getSureDialog
import siau.android.library.KeyString

class OneFragment(var statusBarHeightPx: Int) : NewLazyFragment() {

    constructor() : this(20)

    lateinit var topView: View
    lateinit var appbarLayout: AppBarLayout
    lateinit var tabLayout: TabLayout
    lateinit var viewpager: ViewPager2
    lateinit var changeFamily: ImageView
    private val fragments: SparseArray<NewLazyFragment> = SparseArray()
    private val tabs = ArrayList<String>()
    private var currentPosition = 0
    private var weightFragment: OneFragmentInner? = null
    private var heightFragment: OneFragmentInner? = null
    private var toothBrushFragment: OneFragmentToothBrushInner? = null

    override fun getContentViewId(): Int {
        return R.layout.fragment_one
    }

    override fun initView(view: View?) {
        super.initView(view)
        appbarLayout = view?.findViewById(R.id.fragment_one_app_bar)!!
        tabLayout = view.findViewById(R.id.fragment_one_tab_layout)!!
        viewpager = view.findViewById(R.id.fragment_one_viewpager)!!
        changeFamily = view.findViewById(R.id.fragment_one_change_family)!!

        topView = view.findViewById(R.id.fragment_one_top_view)
        val layoutParams = topView.layoutParams
        layoutParams.height = statusBarHeightPx
        topView.layoutParams = layoutParams
    }

    override fun initData() {
        super.initData()

        var addWeight = false
        var addHeight = false
        var addToothBrush = false
        SBApplication.userData.deviceList?.forEach {
            when (it.deviceType) {
                1 -> {
                    if (!addWeight) {
                        addWeight = true
                        if (weightFragment == null) {
                            weightFragment = OneFragmentInner(OneFragmentInner.PAGE_STATE_WEIGHT, hasOut = true, outShow = true)
                        }
                        fragments.put(fragments.size(), weightFragment)
                        tabs.add(getString(R.string.weight_machine))
                    }
                }
                2 -> {
                    if (!addHeight) {
                        addHeight = true
                        if (heightFragment == null) {
                            heightFragment = OneFragmentInner(OneFragmentInner.PAGE_STATE_HEIGHT, hasOut = true, outShow = true)
                        }
                        fragments.put(fragments.size(), heightFragment)
                        tabs.add(getString(R.string.height_machine))
                    }
                }
                3 -> {
                    if (!addToothBrush) {
                        addToothBrush = true
                        if (toothBrushFragment == null) {
                            toothBrushFragment = OneFragmentToothBrushInner(hasOut = true, outShow = true)
                        }
                        fragments.put(fragments.size(), toothBrushFragment)
                        tabs.add(getString(R.string.tooth_brush_machine))
                    }
                }
            }
        }

        val adapter = activity?.let { AdapterFragmentPager(it, fragments) }

        viewpager.adapter = adapter

        tabs.forEachIndexed { index, value ->
            val tab = tabLayout.newTab()
            tab.text = value
            tabLayout.addTab(tab, index, 0 == index)
        }

        val tm = TabLayoutMediator(tabLayout, viewpager) { tab, position ->
            tab.text = tabs[position]
        }

        tm.attach()
    }

    override fun initEvent() {
        super.initEvent()
        changeFamily.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (!SBApplication.startShowChangeFamilySheet) {
                    SBApplication.startShowChangeFamilySheet = true

                    HttpHelper().getFamilyList()?.compose(RxLifecycle.bindUntilEvent(lifecycle(), FragmentEvent.STOP))?.subscribe({
                        //判断有没有自己创建家庭
                        if (it.hasOwnFamily == 0) {
                            activity?.let { it1 ->
                                getSureDialog(it1, object : OnMultiClickListener() {
                                    override fun onMultiClick(v: View?) {
//                                        if (SBApplication.startCalculate.value == true) {
//                                            SBApplication.startCalculate.value = false
//                                        }
                                        Bus.getDefault().post(KeyString.createSelfFamily)
                                        SBApplication.startShowChangeFamilySheet = false
                                    }
                                }, cancelListener = object : OnMultiClickListener() {
                                    override fun onMultiClick(v: View?) {
                                        val bottomSingleFamilySelectSheet = activity?.let { it1 ->
                                            BottomSingleFamilySelectSheet(it1, it) { it2 ->
//                                                if (SBApplication.startCalculate.value == true) {
//                                                    SBApplication.startCalculate.value = false
//                                                }
                                                val m = activity as MainActivity
                                                m.changeFamily(it2)
                                            }
                                        }
                                        bottomSingleFamilySelectSheet?.show()
                                    }
                                }, content = getString(R.string.sure_to_create_self_family), showTitle = false)
                            }
                        } else {
                            val bottomSingleFamilySelectSheet = activity?.let { it1 ->
                                BottomSingleFamilySelectSheet(it1, it) { it2 ->
//                                    if (SBApplication.startCalculate.value == true) {
//                                        SBApplication.startCalculate.value = false
//                                    }
                                    val m = activity as MainActivity
                                    m.changeFamily(it2)
                                }
                            }
                            bottomSingleFamilySelectSheet?.show()
                        }

                    }, {
                        showToast(it.message)
                        SBApplication.startShowChangeFamilySheet = false
                    })
                }
            }
        })
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                currentPosition = tab?.position ?: -1
                SBApplication.communityChildId = (fragments[currentPosition] as OneFragmentInner).childIdNow
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })

        SBApplication.mainPageChange.observe(this, {
            if (it != null) {
                val childId = it.childId
                val deviceType = it.deviceType
                SBApplication.mainPageChange.value = null

                openPageWithChild(deviceType, childId)
            }
        })
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            if (currentPosition != -1) {
                fragments[currentPosition].isOutShow = true
                fragments[currentPosition].onHiddenChanged(hidden)
            }
        } else {
            if (currentPosition != -1) {
                fragments[currentPosition].isOutShow = false
                fragments[currentPosition].onHiddenChanged(hidden)
            }
        }
    }

    fun openPageWithChild(deviceType: Int, childId: Int) {
        if (deviceType == 1) {//去体重秤页面
            if (weightFragment != null) {
                val index = fragments.indexOfValue(weightFragment)
                viewpager.currentItem = index
                weightFragment!!.selectSomeChild(childId)
            }
        } else if (deviceType == 2) {//去身高仪页面
            if (heightFragment != null) {
                val index = fragments.indexOfValue(heightFragment)
                viewpager.currentItem = index
                heightFragment!!.selectSomeChild(childId)
            }
        } else if (deviceType == 3) {//去牙刷页面
            if (toothBrushFragment != null) {
                val index = fragments.indexOfValue(toothBrushFragment)
                viewpager.currentItem = index
                toothBrushFragment!!.selectSomeChild(childId)
            }
        }
    }
}